<?php
namespace app\common\product\model;


use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;

class ProductRule extends Model
{
    protected $table = "tk_store_product_rule";

    protected $type = [
        'rule_value' => 'json',
    ];

    // 列表中商品规格
    public function getSpecFieldsAttr($value, $data) {
        $ruleValue = json_decode($data['rule_value'], 1);
        $fields = array_column($ruleValue, 'value');
        return implode(',', $fields);
    }

    // 列表中商品规格的值
    public function getSpecValuesAttr($value, $data) {
        $ruleValue = json_decode($data['rule_value'], 1);
        return array_column($ruleValue, 'detail');
    }

    public function getRuleDetailAttr($value, $data): array
    {
        try {
            $model = new ProductRuleValue();
            $where = [];
            $where[] = ['rule_id', '=', $data['id']];
            $where[] = ['parent_id', '>', 0];
            return $model->where($where)->order('id asc')->column('id', 'value');
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            return [];
        }
    }
}